package com.ler.yrmall.aspect;

import com.ler.yrmall.aspect.anno.AccessRecord;
import com.ler.yrmall.constant.YuruoConstant;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author leron
 */
@Aspect
@Component
@ConditionalOnBean(StringRedisTemplate.class)
public class AccessRecordAspect {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Before("@within(accessRecord) || @annotation(accessRecord)")
    public void beforeAccessRecord(AccessRecord accessRecord) {

        String mk = YuruoConstant.MONTH_VISITED_PREFIX + LocalDate.now().getYear();
        BoundHashOperations<String, Object, Object> monthVis = stringRedisTemplate.boundHashOps(mk);
        int monthValue = LocalDate.now().getMonthValue();
        monthVis.increment(String.valueOf(monthValue),1);
        stringRedisTemplate.expire(mk,1, TimeUnit.DAYS);

        String hk = YuruoConstant.HOVER_VISITED_PREFIX + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        BoundHashOperations<String, Object, Object> hoverVis = stringRedisTemplate.boundHashOps(hk);
        int hoverValue = LocalDateTime.now().getHour();
        hoverVis.increment(String.valueOf(hoverValue),1);
        stringRedisTemplate.expire(hk,1, TimeUnit.DAYS);

        String dk = YuruoConstant.DAY_VISITED_PREFIX + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        stringRedisTemplate.opsForValue().increment(dk);
        stringRedisTemplate.expire(dk,30, TimeUnit.DAYS);

        stringRedisTemplate.opsForValue().increment(YuruoConstant.VISITED_PREFIX);
    }
}
